
from querier.esquerier import ElasticSearchQuerier
import utils.utils as utils

MAX_BRANDS = 100


class WechatKOLInfoWithBrandQuerier(ElasticSearchQuerier):
    def _build_query(self, args):
        pass

    def _build_result(self, es_result, param):
        pass

    def __init__(self, kol_info, brand_match):
        super(WechatKOLInfoWithBrandQuerier, self).__init__(None, None, None)
        self.kol_info = kol_info
        self.brand_match = brand_match

    def search(self, args):
        id_ = args.get('biz_code')
        ids_ = args.get('biz_codes')
        if id_ is None and ids_ is None:
            raise ValueError('message: "biz_code" or "biz_codes"(list of "biz_code") is needed')

        if id_:
            return self.get_info(id_)
        else:
            result = [self.get_info(i) for i in ids_]

        kol_result = {"infos": result}
        return kol_result

    def get_info(self, id_):
        kol_info_args = {"biz_code": id_}
        kol_result = self.kol_info.search(kol_info_args)
        if kol_result:
            keywords = kol_result.get('keywords', [])
            kol_result['ex_brands'] = self.get_brands(keywords)
        else:
            kol_result = {}

        return kol_result

    def get_brands(self, keywords):
        args = {
            'term': ' '.join(keywords),
            'from': 0,
            'size': MAX_BRANDS
        }
        brand_result = self.brand_match.search(args)
        brands = [b.get('brand', '') for b in brand_result.get('brands', [])]
        weights = [b.get('score', '') for b in brand_result.get('brands', [])]
        brands = utils.get_kv_json(brands, weights)
        return brands


class WechatKOLInfoQuerier(ElasticSearchQuerier):
    def __init__(self, es, index, doc_type, nlp_service=None):
        super(WechatKOLInfoQuerier, self).__init__(None, None, None)
        self.es = es
        self.index = index
        self.doc_type = doc_type
        self.nlp_service = nlp_service

    def search(self, args):
        id_ = args.get('biz_code')
        ids_ = args.get('biz_codes')
        if id_ is None and ids_ is None:
            raise ValueError('message: "biz_code" or "biz_codes"(list of "biz_code") is needed')
        if id_ is not None:
            try:
                res = self.es.get(index=self.index, doc_type=self.doc_type, id=id_)
            except Exception as e:
                print(str(e))
                res = {"Error": "No such biz_code found: " + str(ids_)}
            return self._build_result(res, None)
        else:
            out = []
            for i in ids_:
                try:
                    res = self.es.get(index=self.index, doc_type=self.doc_type, id=i)
                    res = self._build_result(res, None)
                except Exception as e:
                    print(str(e))
                    res = {"Error": "No such biz_code found: " + str(i)}
                out.append(res)
            return {"infos": out}

    def _build_query(self, args):
        pass

    def _build_result(self, es_result, param):
        if es_result.get('found'):
            source_ = es_result['_source']
            print(source_)
            biz_info = source_['biz_info']

            kol_avatar_url = source_['head_img']
            kol_influence_score = source_['score_cal']
            biz_code = source_['biz_code']
            biz_name = source_['biz_name']

            qr_template = "http://mp.weixin.qq.com/mp/qrcode?scene=10000004&size" \
                          "=102&__biz=%s&mid=%s&idx=%s&sn=%s&send_time="
            bid = source_.get('bid')
            mid = source_.get('mid')
            idx = source_.get('idx')
            sn = source_.get('sn')
            qrcode_url = qr_template % (bid, mid, idx, sn)

            keywords = source_['keywords'][0:10]

            return {
                'biz_name': biz_name,
                'biz_code': biz_code,
                'biz_info': biz_info,
                'qrcode_url': qrcode_url,
                'keywords': keywords,
                'head_img': kol_avatar_url,
                'score': kol_influence_score,
                # 'max_score': [ max_score],
                'sum_read_num': source_['sum_read_num'],
                'avg_read_num': source_['avg_read_num'],
                'max_read_num': source_['max_read_num'],
                'sum_like_num': source_.get('sum_like_num'),
                'avg_like_num': source_.get('avg_like_num'),
                'max_like_num': source_.get('max_like_num'),
                'like_read_ratio': source_.get('like_read_ratio'),
                'categories': [utils.category_smzdm_2_decode(int(c)) for c in source_['categories']],
                'categories_media': [utils.category_media_2_decode(c) for c in source_['categories_media']],
                'timestamp': source_.get('timestamp'),
                'customer_type': source_.get('customer_type'),
                'orig_ratio': source_.get('orig_ratio'),
                'orig_count': source_.get('orig_count'),
                'media_name': source_.get('media_name'),
                'categories_with_weight': utils.get_category_weight(source_['categories'], source_['categories_weight']),
                'keywords_with_weight': '',
                'brands': [],  # self.nlp_service.get_brands(source_.get('keywords', []))
                "verify_date": source_.get('verify_date'),
                "position": source_.get('position')
            }

